/*
 * Copyright (C) 2021 Fastjrun, Inc. All Rights Reserved.
 */
package com.fastjrun.share.demo.web;

import com.fastjrun.apiworld.helper.ResultHelper;
import com.fastjrun.apiworld.vo.ResultModel;
import com.fastjrun.common.ServiceException;
import com.fastjrun.share.demo.common.CodeMsgConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

@ControllerAdvice
public class GlobalExcepitonHandler {

    protected final Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    protected MessageSource serviceMessageSource;


    @ExceptionHandler
    @ResponseBody
    public Object expHandler(Exception e) {
        ResultModel resultModel;
        if (e instanceof ServiceException) {
            resultModel = ResultHelper.fail(Integer.valueOf(((ServiceException) e).getCode()), ((ServiceException) e).getMsg());
        } else {
            resultModel = ResultHelper.fail(Integer.valueOf(CodeMsgConstants.SYSTEM_500_99999), this.serviceMessageSource.getMessage(CodeMsgConstants.SYSTEM_500_99999, null, null));
        }
        return resultModel;
    }
}
